import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { Table, Card, Button, Modal, Input } from 'antd'
import { useEffect } from 'react'
import { loadConfigList, updateConfigById } from './services'
import { useState } from 'react'
import { message } from 'antd'

const Platform = () => {
  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      align: 'center'
    },
    {
      title: '名称',
      dataIndex: 'description',
      align: 'center'
    },
    {
      title: '值',
      dataIndex: 'value',
      align: 'center'
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center'
    },
    {
      title: '操作',
      align: 'center',
      render: (text, record) => (
        <>
          <Button type="primary" onClick={() => onHanlderConfig(record)}>
            编辑
          </Button>
        </>
      )
    }
  ]

  const [confgList, setConfigList] = useState([])
  const [visible, setVisible] = useState(false)

  const [iptValue, setIptValue] = useState('')
  const [record, setRecord] = useState({})

  const handleOk = async () => {
    try {
      if (iptValue.trim().length === 0) {
        return message.warning('输入内容不能为空')
      }
      await updateConfigById({ id: record.id, value: iptValue })
      getConfigList()
      setVisible(false)
      setIptValue('')
      message.success('配置成功')
    } catch (error) {}
  }
  const handleCancel = () => {
    setVisible(false)
    setIptValue('')
  }

  const onHanlderConfig = record => {
    setVisible(true)
    setRecord(record)
  }

  const getConfigList = async () => {
    const { success, data } = await loadConfigList()
    if (success) {
      setConfigList(data)
    }
  }

  useEffect(() => {
    getConfigList()
  }, [])

  const title = () => {
    return `平台相关配置/${record.description}`
  }

  return (
    <PageHeaderWrapper title={false}>
      <Card>
        <Table bordered rowKey="id" dataSource={confgList} columns={columns} />
      </Card>

      <Modal
        title={title()}
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Input
          placeholder="请输入对应值"
          value={iptValue}
          onInput={e => setIptValue(e.target.value)}
        />
      </Modal>
    </PageHeaderWrapper>
  )
}

export default Platform
